//
//  ImageCompressTool.m
//  QQMiniGameSDKDemo
//
//  Created by Goyoungs on 2023/5/24.
//

#import "ImageCompressTool.h"
@implementation ImageCompressTool
#pragma mark - 图片压缩

+ (CGFloat)getCompressRateByImageSize:(CGFloat)imageSize targetSize:(CGFloat)targetSize {
    NSUInteger rate = (NSUInteger)(imageSize / targetSize);
    rate = (rate == 0) ? 1 : rate;

    // 默认0.8压缩因子
    CGFloat maxCompressRate = 0.8;
    CGFloat minCompressRate = 0.2;

    // 反比例压缩函数
    CGFloat compressRate = 0.8 / rate;

    compressRate = MIN(MAX(compressRate, minCompressRate), maxCompressRate);
    return compressRate;
}

+ (NSData *)compressImageSize:(UIImage *)image toByte:(NSUInteger)maxLength times:(NSInteger)times {
    NSData *data = UIImageJPEGRepresentation(image, 1);
    if (data.length < maxLength) {
        return data;
    }

    CGFloat compressRate = [self.class getCompressRateByImageSize:data.length targetSize:maxLength];
    data = UIImageJPEGRepresentation(image, compressRate);
    if (data.length < maxLength) {
        return data;
    }

    UIImage *resultImage = [UIImage imageWithData:data];
    NSUInteger lastDataLength = 0;
    NSInteger count = 0;
    while (data.length > maxLength && data.length != lastDataLength && count < times) {
        lastDataLength = data.length;
        CGFloat ratio = (CGFloat)maxLength / data.length;
        CGSize size = CGSizeMake((NSUInteger)(resultImage.size.width * sqrtf(ratio)), (NSUInteger)(resultImage.size.height * sqrtf(ratio)));
        if (CGSizeEqualToSize(size, CGSizeZero) || size.width < 10 || size.height < 10) {
            break;
        }
        UIGraphicsBeginImageContext(size);
        [resultImage drawInRect:CGRectMake(0, 0, size.width, size.height)];
        resultImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        data = UIImageJPEGRepresentation(resultImage, compressRate);
        count = count + 1;
    }

    return data;
}


@end
